package top.banner.contentcenter.service.content;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.banner.contentcenter.dao.rocketmqtransactionlog.RocketmqTransactionLogMapper;
import top.banner.contentcenter.dao.share.ShareMapper;
import top.banner.contentcenter.domain.dto.content.ShareAuditDTO;
import top.banner.contentcenter.domain.dto.content.ShareDTO;
import top.banner.contentcenter.domain.dto.messaging.UserAddBonusMsgDTO;
import top.banner.contentcenter.domain.dto.user.UserDTO;
import top.banner.contentcenter.domain.entity.rocketmqtransactionlog.RocketmqTransactionLog;
import top.banner.contentcenter.domain.entity.share.Share;
import top.banner.contentcenter.domain.enums.AuditStatusEnum;
import top.banner.contentcenter.feignclient.UserCenterFeignClient;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

/**
 * @author XGL
 */
@Service
@Slf4j
public class ShareService {

    @Resource
    private ShareMapper shareMapper;
    @Resource
    private UserCenterFeignClient userCenterFeignClient;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private RocketmqTransactionLogMapper rocketmqTransactionLogMapper;
    @Resource
    private Source source;

    /**
     * 根据ID获取分享详情。
     *
     * @param id id
     */
    public ShareDTO findById(Integer id) {
        Share share = shareMapper.selectByPrimaryKey(id);

        Integer userId = share.getUserId();

//        UserDTO userDTO = restTemplate.getForObject("http://user-center/users/{id}",
//                UserDTO.class, userId);
        final UserDTO userDTO = userCenterFeignClient.findById(userId);

        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share, shareDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());
        return shareDTO;
    }

    public Share auditById(Integer id, ShareAuditDTO auditDTO) {
        Share share = shareMapper.selectByPrimaryKey(id);
        if (share == null) {
            throw new IllegalArgumentException("参数非法！该分享不存在！");
        }
        if (!Objects.equals(AuditStatusEnum.NOT_YET.toString(), share.getAuditStatus())) {
            throw new IllegalArgumentException("参数非法！该分享已审核通过！");
        }

        if (AuditStatusEnum.PASS.equals(auditDTO.getAuditStatusEnum())) {//审核通过
            //如果审核通过，发送消息给MQ，增加积分
            String transactionId = UUID.randomUUID().toString();

            this.source.output()
                    .send(MessageBuilder.withPayload(UserAddBonusMsgDTO.builder()
                                    .userId(share.getUserId())
                                    .bonus(50)
                                    .build())
                            .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                            .setHeader("share_id", id)
                            .setHeader("dto", JSON.toJSONString(auditDTO))
                            .build());

            //rocketMQTemplate.sendMessageInTransaction(
            //        "tx-add-bonus-group",
            //        "add-bonus",
            //        MessageBuilder.withPayload(UserAddBonusMsgDTO.builder()
            //                        .userId(share.getUserId())
            //                        .bonus(50)
            //                        .build())
            //                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
            //                .setHeader("share_id", id)
            //                .build(),
            //        auditDTO
            //);
        } else {//审核失败
            auditByIdInDB(id, auditDTO);
        }

        return share;
    }

    /**
     * 审核资源
     *
     * @param id id
     */
    @Transactional
    public void auditByIdInDB(Integer id, ShareAuditDTO auditDTO) {
        Share share = Share.builder()
                .id(id)
                .auditStatus(auditDTO.getAuditStatusEnum().toString())
                .reason(auditDTO.getReason())
                .build();
        shareMapper.updateByPrimaryKeySelective(share);
    }


    /**
     * 审核资源，并记录 MQ事务日志
     *
     * @param id id
     */
    @Transactional
    public void auditByIdWithRocketMQLog(Integer id, ShareAuditDTO auditDTO, String transactionId) {
        auditByIdInDB(id, auditDTO);

        rocketmqTransactionLogMapper.insert(
                RocketmqTransactionLog.builder()
                        .transactionId(transactionId)
                        .log("审核分享")
                        .build()
        );
    }
}
